import friends
import gtk

class appFriend:
    """friend manage application class"""
    def __init__(self):
        builder = gtk.Builder()
        builder.add_from_file("ui/friends.glade")
        self._dialog = builder.get_object("manageFriendsDialog")
        self._groupDialog = builder.get_object("addGroupDialog")
        self._friendsTreeView = builder.get_object("friendsTreeview")
        builder.connect_signals(self)   
        self._listStore = builder.get_object("friendsListstore")
        self._groupListStore = builder.get_object("groupsListstore")
        self._groupComboboxentry = builder.get_object("groupComboboxentry")
        self.refreshFriendsList()
        self.refreshGroupsList()
            
    def on_quitButton_clicked(self,widget,data=None):
        self._dialog.destroy()
    
    def on_friendDelAction_activate(self,widget,data=None):
        selected = self._friendsTreeView.get_selection().get_selected_rows()[1]
        for rowSelected in selected:
            ID = self._listStore.get_value(self._listStore.get_iter(rowSelected),2)
            if not friends.getFriendsPool().delFriend(ID):
                errMsgBox("Error","Unable to delete friend with ID %s)"%ID)
        self.refreshFriendsList()
        
    def on_friendAddAction_activate(self,widget,data=None):
        fc = gtk.FileChooserDialog("Save my account as a contact",None,gtk.FILE_CHOOSER_ACTION_OPEN,(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        filter = gtk.FileFilter()
        filter.add_pattern("*.dat")
        fc.set_filter(filter)
        if fc.run() == gtk.RESPONSE_ACCEPT:     
            try:   
                friends.getFriendsPool().importFriendFromFile(fc.get_filename())
            except information.informationError, e:
                errMsgBox("Add friend error",str(e))
        fc.destroy()
        self.refreshFriendsList()
        
    def refreshFriendsList(self):
        #populate liststore
        self._listStore.clear()
        for f in friends.getFriendsPool().getAllFriends():
            #convert groups to string
            gs = ""
            for group in f.getGroups():
                gs += group.getName() + ";"
            #append to liststore
            self._listStore.append((f.getName(),gs,f.getID()))
    
    def refreshGroupsList(self):
        #populate liststore
        self._groupListStore.clear()
        for g in friends.getFriendsPool().getAllFriendsGroup():
            #append to liststore
            self._groupListStore.append((g.getName(),g.getID()))
            
    def on_friendAddGroupAction_activate(self,widget,data=None):
        if self._friendsTreeView.get_selection().get_selected()[1]:
            self._groupDialog.run()
        
    def on_groupCancelAction_activate(self,widget,data=None):
         self._groupDialog.hide()
        
    def on_groupOKAction_activate(self,widget,data=None):
        if self._groupComboboxentry.get_active_iter(): #if group already in list
            groupID = self._groupListStore.get_value(self._groupComboboxentry.get_active_iter(),1)
            group = friends.getFriendsPool().getMyFriendsGroup(groupID)
        elif self._groupComboboxentry.child.get_text(): #if not a new group is created
            group = friends.getFriendsPool().createGroup(self._groupComboboxentry.child.get_text())
        else:
            return
        friendID = self._listStore.get_value(self._friendsTreeView.get_selection().get_selected()[1],2)
        group.appendByID(friendID)
        self._groupDialog.hide()
        self.refreshFriendsList()
        return
    
    def on_friendResetGroupAction_activate(self,widget,data=None):
        if self._friendsTreeView.get_selection().get_selected()[1]:
            friendID = self._listStore.get_value(self._friendsTreeView.get_selection().get_selected()[1],2)
            friendObject = friends.getGlobalAccount(friendID)
            for groupObject in friendObject.getGroups():
                #filter only group own by user
                try:
                    myGroupObject = friends.getFriendsPool().getMyFriendsGroup(groupObject.getID())
                except:
                    continue
                #remove membership
                myGroupObject.remove(friendObject)
            self.refreshFriendsList()
